package com.huixi.microspur.web.aspect;

import com.huixi.microspur.commons.enums.ErrorCodeEnum;
import com.huixi.microspur.commons.exception.BusinessException;
import com.huixi.microspur.commons.util.wrapper.WrapMapper;
import com.huixi.microspur.commons.util.wrapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * <p>
 * 全局异常处理器
 * </p>
 *
 * @author xzl
 * @since 2020-01-16
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数非法异常.
     *
     * @param e the e
     * @return the wrapper
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<String> constraintViolationException(MethodArgumentNotValidException e) {
        log.error("参数非法异常={}", e.getMessage());
        return WrapMapper.wrap(ErrorCodeEnum.GL99990500.code(),
                e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 业务异常
     *
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Wrapper<String> myException(BusinessException e) {
        log.error("业务异常={}", e.getMessage(), e);
        return WrapMapper.wrap(e.getCode() == 0 ? Wrapper.ERROR_CODE : e.getCode(), e.getMessage());
    }

    /**
     * 全局异常
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Wrapper<Object> exception(Exception e) {
        log.error("全局异常={}", e.getMessage(), e);
        //可做入库处理
        return WrapMapper.error();
    }

}
